// pages/scan/scan.js
Page({
  // 设备缓存，因为这是一个窗口页面，生命周期较短，这里会一直缓存到unload
  deviceCache: new Map(),
  // 记录设备排序，如果没有手动排过序，就是FIFO原则
  sortedAddresses: [],
  data: {
    bluetoothState: {
      available: false,
      discovering: false
    },
    bleDevices: [], //{name:"N/A",mac:"FF:FF:FF:FF:FF:FF",rssi:-127}
    scrollViewHeight: 200,
    rssiThreshold: -127
  },
  onSliderChanged: function (res) {
    console.log(res.detail.value)
    this.setData({
      rssiThreshold: res.detail.value
    })
  },
  //res = {available: false, discovering: false}
  onBluetoothAdapterChanged: function (res) {
    this.setData({
      bluetoothState: res
    })
  },
  onDeviceFound(res) {
    this.appendDevices(res.devices)
    this.updateUI()
  },
  appendDevices(devices) {
    let that = this
    //把最新发现的设备放入缓存中（只过滤不可连接设备）
    devices.forEach(device => {
      //todo device.connectable (Android 8.0 以下不支持返回该值)
      if ((device.connectable == null) || (device.connectable == true)) {
        if (!that.deviceCache.has(device.deviceId)) {
          that.sortedAddresses.push(device.deviceId)
        }
        that.deviceCache.set(device.deviceId, device)
      }
    })
  },
  updateUI() {
    //从缓存列表中
    let newBleDevices = []
    for (let mac of this.sortedAddresses) {
      let device = this.deviceCache.get(mac) //todo null or not
      if (device != null) {
        var _name = "N/A"
        if (device.name != null && device.name.length != 0) {
          _name = device.name
        } else if (device.localName != null && device.localName.length != 0) {
          _name = device.localName
        }
        var _image = "../../image/signal_poor.png"
        if (device.RSSI > -60) {
          _image = "../../image/signal_full_case.png"
        } else if (device.RSSI > -90) {
          _image = "../../image/signal_general.png"
        }
        let bleDevice = {
          name: _name,
          deviceId: device.deviceId,
          rssi: device.RSSI,
          rssiRes: _image
        }
        newBleDevices.push(bleDevice)
      }
    }
    this.setData({
      bleDevices: newBleDevices
    })
  },
  sortByRssi() {
    let array = []
    let that = this
    this.deviceCache.forEach(function (value, key) {
      array.push(value)
    })
    array.sort(function (a, b) {
      return (b.RSSI - a.RSSI)
    })
    console.log(array.length)
    this.sortedAddresses = array.map(function (value) {
      return value.deviceId
    })
    this.updateUI()
  },
  onSelected(e) {
    let curPages = getCurrentPages()
    let prevPage = curPages[curPages.length -2]
    prevPage.onDeviceSelected(e.currentTarget.dataset.item.deviceId)
    wx.navigateBack()
  },
  onLoad(options) {
    let that = this
    wx.onBluetoothAdapterStateChange(this.onBluetoothAdapterChanged)
    wx.onBluetoothDeviceFound(this.onDeviceFound)
    wx.openBluetoothAdapter({
      success(res) {
        that.startScan()
        that.setData({
          bluetoothState: {
            available: true
          }
        })
      },
      fail(err) {
        console.error(err)
      }
    })
    this.calViewHeight()
  },
  startScan() {
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      interval: 1000,
      powerLevel: 'high'
    })
  },
  stopScan() {
    wx.stopBluetoothDevicesDiscovery()
  },
  onReady() {
    this.calViewHeight()
  },
  onUnload() {
    this.stopScan()
    wx.offBluetoothDeviceFound(this.onDeviceFound)
    wx.offBluetoothAdapterStateChange(this.onBluetoothAdapterChanged)
    this.deviceCache.clear()
    this.sortedAddresses = []
  },
  calViewHeight() {
    let that = this
    var item = wx.createSelectorQuery();
    item.selectAll('.fixedHeight').boundingClientRect() //里面需要绑定 view组件的id
    item.exec(function (res) { //res为绑定元素信息的数组
      var height = 0
      if (res.length == 0) {
        return
      }
      let result = res[0]
      for (var i = 0; i < result.length; i++) {
        let view = result[i]
        height += view.height
      }
      let scollViewHeight = wx.getSystemInfoSync().windowHeight - height
      that.setData({
        scrollViewHeight: scollViewHeight * 0.90
      })
    })
  }

})